package com.sun.wanandroid.ui.login

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.sun.module_base.app.BaseViewModel
import com.sun.module_base.app.ResultState
import com.sun.module_base.ext.showToast
import com.sun.module_common.model.UserInfo
import com.sun.module_network.utils.loge
import com.sun.wanandroid.net.HttpRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

/**
 *@author:sunc
 *@time :2025/7/28 17:27
 *@desc: 描述
 */
@HiltViewModel
class LoginViewModel @Inject constructor(private val httpRepository: HttpRepository) :
    BaseViewModel() {
    var userName by mutableStateOf("")
    var passWord by mutableStateOf("")
    var passWordConfirm by mutableStateOf("")

    var isLoading by mutableStateOf(false)

    private val _loginFlow =
        MutableStateFlow<ResultState<UserInfo?>>(ResultState.Loading())

    // 将 MutableStateFlow 转换为 StateFlow，以便在 Composable 中观察
    val loginFlow = _loginFlow.asStateFlow()

    private val _registerFlow =
        MutableStateFlow<ResultState<UserInfo?>>(ResultState.Loading())

    // 将 MutableStateFlow 转换为 StateFlow，以便在 Composable 中观察
    val registerFlow = _registerFlow.asStateFlow()

    fun login() {
        if (userName.isEmpty() || passWord.isEmpty()) {
            showToast("用户名或密码为空！")
            return
        }

        "login点击".loge()
        isLoading = true
        launchUI({ httpRepository.login(userName.trim(), passWord.trim()) }, _loginFlow)
    }


    fun register() {
        if (userName.isEmpty() || passWord.isEmpty() || passWordConfirm.isEmpty()) {
            showToast("用户名或密码为空！")
            return
        }
        if (passWord.trim() != passWordConfirm.trim()) {
            showToast("两次密码不一致，请重新输入")
            return
        }

        "login点击".loge()
        isLoading = true
        launchUI({
            httpRepository.register(
                userName = userName.trim(),
                passWord = passWord.trim(),
                repassWord = passWordConfirm.trim()
            )
        }, _registerFlow)
    }
}